import areaData from 'china-area-data'

type AreaDataType = {
  [key: string]: {
    [key: string]: string
  } | string
}

const typedAreaData = areaData as unknown as AreaDataType

// 获取所有省份数据
export const getProvinces = () => {
  const provinces = typedAreaData['86'] as { [key: string]: string }
  return Object.entries(provinces).map(([code, name]) => ({
    code,
    name
  }))
}

// 获取指定省份的城市数据
export const getCities = (provinceCode: string) => {
  const cities = typedAreaData[provinceCode] as { [key: string]: string }
  if (!cities) return []
  
  return Object.entries(cities).map(([code, name]) => ({
    code,
    name
  }))
}

// 获取指定城市的区县数据
export const getDistricts = (cityCode: string) => {
  const districts = typedAreaData[cityCode] as { [key: string]: string }
  if (!districts) return []
  
  return Object.entries(districts).map(([code, name]) => ({
    code,
    name
  }))
}

// 根据编码获取地区名称
export const getAreaName = (code: string) => {
  if (!code) return ''
  
  // 尝试直接从typedAreaData获取名称
  const area = typedAreaData[code]
  if (typeof area === 'string') {
    return area
  }
  
  // 如果code是省份代码，尝试从86（中国）下获取
  if (code.length === 6 && code.endsWith('0000')) {
    const provinceCode = code.substring(0, 2)
    const provinces = typedAreaData['86'] as { [key: string]: string }
    return provinces[code] || ''
  }
  
  // 如果code是城市代码，尝试从省份下获取
  if (code.length === 6 && code.endsWith('00')) {
    const provinceCode = code.substring(0, 2) + '0000'
    const cities = typedAreaData[provinceCode] as { [key: string]: string }
    return cities[code] || ''
  }
  
  // 如果code是区县代码，尝试从城市下获取
  if (code.length === 6) {
    const cityCode = code.substring(0, 4) + '00'
    const districts = typedAreaData[cityCode] as { [key: string]: string }
    return districts[code] || ''
  }
  
  return ''
}

interface RegionOption {
  value: string
  label: string
  children?: RegionOption[]
}

// 获取完整的地区数据（用于级联选择器）
export const getFullAreaData = (): RegionOption[] => {
  const provinces = typedAreaData['86'] as { [key: string]: string }
  const options: RegionOption[] = []
  
  for (const provinceCode in provinces) {
    const province: RegionOption = {
      value: provinceCode,
      label: provinces[provinceCode],
      children: []
    }
    
    const cities = typedAreaData[provinceCode] as { [key: string]: string }
    if (cities) {
      for (const cityCode in cities) {
        const city: RegionOption = {
          value: cityCode,
          label: cities[cityCode],
          children: []
        }
        
        const districts = typedAreaData[cityCode] as { [key: string]: string }
        if (districts) {
          for (const districtCode in districts) {
            city.children?.push({
              value: districtCode,
              label: districts[districtCode]
            })
          }
        }
        
        province.children?.push(city)
      }
    }
    
    options.push(province)
  }
  
  return options
} 